package org.jeecg.modules.controller;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhyd.oauth.utils.UuidUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.dto.FileUploadUpgrade;
import org.jeecg.modules.utils.AliPayKit;
import org.jeecg.modules.utils.FileUtils;
import org.jeecg.modules.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Validated
@RestController
@RequestMapping("/Upload")
@PropertySource("classpath:application.yml")
@Api(value = "文件上传下载管理", description = "文件上传下载管理", tags = {"FileUploadController"})
public class FileUploadController {

    @Value("${jeecg.path.upload}")
    public String upload;

    public String getUpload() {
        return upload;
    }

    public void setUpload(String upload) {
        this.upload = upload;
    }

    @Value("${application.domain}")
    public String domain;

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }


    @ApiOperation(value = "上传", notes = "上传")
    @RequestMapping(value = "/oneUpload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            //对文文件的全名进行截取然后在后缀名进行删选。
            int begin = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            int last = file.getOriginalFilename().length();
            //获得文件后缀名
            String a = file.getOriginalFilename().substring(begin, last);

            String path="";
            if (a.equals(".bmp")||a.equals(".jpg")||a.equals(".png")||a.equals(".gif")||a.equals(".JPEG")){
                path = "img/";
            }else if (a.equals(".apk")){
                path = "back/apk/";
            }else if (a.equals(".ipa")){
                path = "back/ios/";
            }else{
                path = "back/files/";
            }

            String uploadUrl=upload+path;

            String filename = UuidUtils.getUUID();
            String fileHName = file.getOriginalFilename();

            //判断相应路径是否存在，不存在则创建
            File dir = new File(uploadUrl);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File targetFile = new File(uploadUrl + filename+a);
            if (!targetFile.exists()) {
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //移动上传文件
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }


            return "/bike/files/resources/"+ path + filename + a;

        }else {
            return null;
        }
    }

    /**
     * @param checkCode 网关车桩程序校验码
     * @param appId 上传文件类型 100001用户端android，100002用户端IOS，100003运维端android，100004硬件网点，100005硬件车桩
     * */
    @ApiOperation(value = "版本文件上传", notes = "版本文件上传")
    @RequestMapping(value = "/oneUploadUpgrade", method = RequestMethod.POST)
    public Result<?> oneUploadUpgrade(@RequestParam("file") MultipartFile file,
                                      @RequestParam(value = "checkCode",required = false)String checkCode,
                                      @RequestParam("appId")String appId) throws IOException {
        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            //对文文件的全名进行截取然后在后缀名进行删选。
            int begin = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            int last = file.getOriginalFilename().length();
            //获得文件后缀名
            if (begin<0){
                begin=0;
            }
            String a = file.getOriginalFilename().substring(begin, last);
            String path="";
            FileUploadUpgrade fileUploadUpgrade = new FileUploadUpgrade();
            if (appId.equals("100001")){
                if (!a.equals(".apk")&&!a.equals(".wgt") ) {
                    return Result.error("文件不符合");
                }
                path = "version/user/";
            } else if (appId.equals("100002")){
                if (!a.equals(".ipa")&&!a.equals(".wgt") ) {
                    return Result.error("文件不符合");
                }
                path = "version/ios/";
            } else if (appId.equals("100003")) {
                if (!a.equals(".apk")&&!a.equals(".wgt") ) {
                    return Result.error("文件不符合");
                }
                path = "version/staff/";
            } else if (appId.equals("100004") ) {
                //排除已知类型文件
                path = "version/ftp/firmware/";
                String fileCheckCode = MD5Utils.bytesToMd5String(bytes);
                if (!fileCheckCode.equals(checkCode)) {
                    return Result.error("文件密钥校验未通过,请检查密钥！");
                }
                fileUploadUpgrade.setFile(bytes);
            }else if (appId.equals("100005")){
                //排除已知类型文件
                path = "version/ftp/firmware/";
                String fileCheckCode = MD5Utils.bytesToMd5PileString(bytes);
                if (!fileCheckCode.equals(checkCode)) {
                    return Result.error("文件密钥校验未通过,请检查密钥！");
                }
                fileUploadUpgrade.setFile(bytes);
            }
            String uploadUrl=upload+path;
            String filename = file.getOriginalFilename();
            //判断相应路径是否存在，不存在则创建
            File dir = new File(uploadUrl);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File targetFile = new File(uploadUrl + filename);
            if (!targetFile.exists()) {
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //移动上传文件
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileUploadUpgrade.setUrl("/bike/files/resources/"+ path + filename);
            fileUploadUpgrade.setFileName(filename);
            return Result.OK(fileUploadUpgrade);

        }else {
            return null;
        }
    }
    @ApiOperation(value = "富文本上传", notes = "富文本上传")
    @RequestMapping(value = "/uploadRichText", method = RequestMethod.POST)
    public Result<?> uploadRichText(@RequestParam("file") MultipartFile file) {


        if (!file.isEmpty()) {
            //对文文件的全名进行截取然后在后缀名进行删选。
            int begin = file.getOriginalFilename().indexOf(".");
            int last = file.getOriginalFilename().length();
            //获得文件后缀名
            String a = file.getOriginalFilename().substring(begin, last);

            String path="";
            if (a.equals(".bmp")||a.equals(".jpg")||a.equals(".png")||a.equals(".gif")||a.equals(".JPEG")){
                path = "img/";
            }else if (a.equals(".apk")){
                path = "back/apk/";
            }else if (a.equals(".ipa")){
                path = "back/ios/";
            }else{
                path = "back/files/";
            }
            String uploadUrl=upload+path;

            String filename = UuidUtils.getUUID();
            String fileHName = file.getOriginalFilename();

            //判断相应路径是否存在，不存在则创建
            File dir = new File(uploadUrl);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File targetFile = new File(uploadUrl + filename +a);
            if (!targetFile.exists()) {
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //移动上传文件
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }


            return Result.ok(domain+"/bike/files/resources/"+ path + filename+a);

        }else {
            return Result.error("上传失败");
        }


    }


}
